#include "serverui.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QSettings>
#include <QScrollBar>
#include <QDateTime>
#include <QScreen>
#include <QStyle>
#include <QGuiApplication>

ServerUI::ServerUI(QWidget *parent) : QMainWindow(parent)
{
    // 创建服务器对象
    server = new Server(this);
    
    // 设置UI
    setupUi();
    
    // 连接信号
    connect(server, &Server::serverStatusChanged, this, &ServerUI::onServerStatusChanged);
    connect(server, &Server::clientConnected, this, &ServerUI::onClientConnected);
    connect(server, &Server::clientDisconnected, this, &ServerUI::onClientDisconnected);
    connect(server, &Server::mouseEventReceived, this, &ServerUI::onMouseEventReceived);
    connect(server, &Server::keyboardEventReceived, this, &ServerUI::onKeyboardEventReceived);
    connect(server, &Server::errorOccurred, this, &ServerUI::onErrorOccurred);
    
    // 创建日志更新定时器
    logUpdateTimer = new QTimer(this);
    connect(logUpdateTimer, &QTimer::timeout, this, &ServerUI::updateLog);
    logUpdateTimer->start(1000); // 每秒更新一次日志
    
    // 加载设置
    loadSettings();
    
    LOG_INFO("服务器UI初始化完成");
}

ServerUI::~ServerUI()
{
    saveSettings();
    
    if (server->isRunning()) {
        server->stop();
    }
}

void ServerUI::closeEvent(QCloseEvent *event)
{
    if (server->isRunning()) {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "确认退出", 
                                       "服务器正在运行，确定要退出吗？",
                                       QMessageBox::Yes | QMessageBox::No);
        
        if (reply == QMessageBox::Yes) {
            server->stop();
        } else {
            event->ignore();
            return;
        }
    }
    
    saveSettings();
    event->accept();
}

void ServerUI::setupUi()
{
    // 设置窗口标题和大小
    setWindowTitle("Hand-in-Hand 远程桌面服务器");
    resize(800, 600);
    
    // 创建中央窗口部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    // 创建主布局
    mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(10);
    
    // 创建顶部控制面板
    controlPanel = new QWidget();
    controlLayout = new QHBoxLayout(controlPanel);
    
    startButton = new QPushButton("启动服务器");
    stopButton = new QPushButton("停止服务器");
    stopButton->setEnabled(false);
    statusLabel = new QLabel("服务器未运行");
    
    controlLayout->addWidget(startButton);
    controlLayout->addWidget(stopButton);
    controlLayout->addWidget(statusLabel, 1);
    
    mainLayout->addWidget(controlPanel);
    
    // 创建设置组
    settingsGroup = new QGroupBox("服务器设置");
    settingsLayout = new QVBoxLayout(settingsGroup);
    
    // 端口设置
    portLayout = new QHBoxLayout();
    portLabel = new QLabel("监听端口:");
    portSpinBox = new QSpinBox();
    portSpinBox->setRange(1024, 65535);
    portSpinBox->setValue(5900);
    
    portLayout->addWidget(portLabel);
    portLayout->addWidget(portSpinBox);
    portLayout->addStretch();
    
    settingsLayout->addLayout(portLayout);
    
    // 局域网发现设置
    lanLayout = new QHBoxLayout();
    lanDiscoveryCheckBox = new QCheckBox("启用局域网发现服务");
    lanDiscoveryCheckBox->setChecked(true);
    serverNameLabel = new QLabel("服务器名称:");
    serverNameEdit = new QLineEdit();
    serverNameEdit->setText(server->getServerName());
    
    lanLayout->addWidget(lanDiscoveryCheckBox);
    lanLayout->addWidget(serverNameLabel);
    lanLayout->addWidget(serverNameEdit);
    
    settingsLayout->addLayout(lanLayout);
    
    // 捕获设置
    captureLayout = new QHBoxLayout();
    frameRateLabel = new QLabel("捕获帧率:");
    frameRateSpinBox = new QSpinBox();
    frameRateSpinBox->setRange(1, 60);
    frameRateSpinBox->setValue(10);
    frameRateSpinBox->setSuffix(" fps");
    
    qualityLabel = new QLabel("压缩质量:");
    qualitySpinBox = new QSpinBox();
    qualitySpinBox->setRange(1, 100);
    qualitySpinBox->setValue(80);
    qualitySpinBox->setSuffix(" %");
    
    diffEncodingCheckBox = new QCheckBox("使用差分编码");
    diffEncodingCheckBox->setChecked(true);
    
    captureLayout->addWidget(frameRateLabel);
    captureLayout->addWidget(frameRateSpinBox);
    captureLayout->addWidget(qualityLabel);
    captureLayout->addWidget(qualitySpinBox);
    captureLayout->addWidget(diffEncodingCheckBox);
    captureLayout->addStretch();
    
    settingsLayout->addLayout(captureLayout);
    
    // 控制设置
    controlSettingsLayout = new QHBoxLayout();
    remoteControlCheckBox = new QCheckBox("允许远程控制");
    remoteControlCheckBox->setChecked(true);
    
    controlSettingsLayout->addWidget(remoteControlCheckBox);
    controlSettingsLayout->addStretch();
    
    settingsLayout->addLayout(controlSettingsLayout);
    
    mainLayout->addWidget(settingsGroup);
    
    // 创建选项卡组件
    tabWidget = new QTabWidget();
    
    // 客户端选项卡
    clientsTab = new QWidget();
    clientsLayout = new QVBoxLayout(clientsTab);
    
    clientListWidget = new QListWidget();
    disconnectClientButton = new QPushButton("断开选中客户端");
    disconnectClientButton->setEnabled(false);
    
    clientsLayout->addWidget(clientListWidget);
    clientsLayout->addWidget(disconnectClientButton);
    
    tabWidget->addTab(clientsTab, "客户端列表");
    
    // 日志选项卡
    logTab = new QWidget();
    logLayout = new QVBoxLayout(logTab);
    
    logTextEdit = new QTextEdit();
    logTextEdit->setReadOnly(true);
    
    logLayout->addWidget(logTextEdit);
    
    tabWidget->addTab(logTab, "日志");
    
    mainLayout->addWidget(tabWidget, 1);
    
    // 创建状态栏
    statusBar()->showMessage("就绪");
    
    // 连接按钮信号
    connect(startButton, &QPushButton::clicked, this, &ServerUI::onStartButtonClicked);
    connect(stopButton, &QPushButton::clicked, this, &ServerUI::onStopButtonClicked);
    connect(disconnectClientButton, &QPushButton::clicked, this, &ServerUI::onDisconnectClientClicked);
    
    // 连接设置变更信号
    connect(portSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &ServerUI::onPortChanged);
    connect(frameRateSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &ServerUI::onFrameRateChanged);
    connect(qualitySpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &ServerUI::onQualityChanged);
    connect(diffEncodingCheckBox, &QCheckBox::toggled, this, &ServerUI::onDiffEncodingToggled);
    connect(remoteControlCheckBox, &QCheckBox::toggled, this, &ServerUI::onRemoteControlToggled);
    connect(lanDiscoveryCheckBox, &QCheckBox::toggled, this, &ServerUI::onLANDiscoveryToggled);
    connect(serverNameEdit, &QLineEdit::editingFinished, this, &ServerUI::onServerNameChanged);
    
    // 连接客户端列表信号
    connect(clientListWidget, &QListWidget::itemSelectionChanged, [this]() {
        disconnectClientButton->setEnabled(!clientListWidget->selectedItems().isEmpty());
    });
}

void ServerUI::loadSettings()
{
    QSettings settings("HandInHand", "Server");
    
    // 加载窗口设置
    if (settings.contains("window/size")) {
        resize(settings.value("window/size").toSize());
    }
    
    if (settings.contains("window/pos")) {
        move(settings.value("window/pos").toPoint());
    }
    
    // 加载服务器设置
    if (settings.contains("server/port")) {
        portSpinBox->setValue(settings.value("server/port").toInt());
    }
    
    if (settings.contains("server/frameRate")) {
        frameRateSpinBox->setValue(settings.value("server/frameRate").toInt());
    }
    
    if (settings.contains("server/quality")) {
        qualitySpinBox->setValue(settings.value("server/quality").toInt());
    }
    
    if (settings.contains("server/diffEncoding")) {
        diffEncodingCheckBox->setChecked(settings.value("server/diffEncoding").toBool());
    }
    
    if (settings.contains("server/remoteControl")) {
        remoteControlCheckBox->setChecked(settings.value("server/remoteControl").toBool());
    }
    
    if (settings.contains("server/lanDiscovery")) {
        lanDiscoveryCheckBox->setChecked(settings.value("server/lanDiscovery").toBool());
    }
    
    if (settings.contains("server/serverName")) {
        serverNameEdit->setText(settings.value("server/serverName").toString());
    }
    
    // 应用设置到服务器
    server->setRemoteControlEnabled(remoteControlCheckBox->isChecked());
    server->enableLANDiscovery(lanDiscoveryCheckBox->isChecked());
    server->setServerName(serverNameEdit->text());
}

void ServerUI::saveSettings()
{
    QSettings settings("HandInHand", "Server");
    
    // 保存窗口设置
    settings.setValue("window/size", size());
    settings.setValue("window/pos", pos());
    
    // 保存服务器设置
    settings.setValue("server/port", portSpinBox->value());
    settings.setValue("server/frameRate", frameRateSpinBox->value());
    settings.setValue("server/quality", qualitySpinBox->value());
    settings.setValue("server/diffEncoding", diffEncodingCheckBox->isChecked());
    settings.setValue("server/remoteControl", remoteControlCheckBox->isChecked());
    settings.setValue("server/lanDiscovery", lanDiscoveryCheckBox->isChecked());
    settings.setValue("server/serverName", serverNameEdit->text());
}

void ServerUI::onStartButtonClicked()
{
    quint16 port = portSpinBox->value();
    
    // 启动服务器
    if (server->start(port)) {
        // 更新UI状态
        startButton->setEnabled(false);
        stopButton->setEnabled(true);
        portSpinBox->setEnabled(false);
        
        statusLabel->setText(QString("服务器运行中 - 端口: %1").arg(port));
        statusBar()->showMessage("服务器已启动");
    } else {
        QMessageBox::critical(this, "错误", "无法启动服务器，请检查端口是否被占用");
    }
}

void ServerUI::onStopButtonClicked()
{
    // 停止服务器
    server->stop();
    
    // 更新UI状态将在onServerStatusChanged中处理
}

void ServerUI::onServerStatusChanged(bool running)
{
    if (running) {
        startButton->setEnabled(false);
        stopButton->setEnabled(true);
        portSpinBox->setEnabled(false);
        lanDiscoveryCheckBox->setEnabled(false);
        serverNameEdit->setEnabled(false);
        
        statusLabel->setText(QString("服务器运行中 - 端口: %1").arg(portSpinBox->value()));
        statusBar()->showMessage("服务器已启动");
    } else {
        startButton->setEnabled(true);
        stopButton->setEnabled(false);
        portSpinBox->setEnabled(true);
        lanDiscoveryCheckBox->setEnabled(true);
        serverNameEdit->setEnabled(true);
        
        statusLabel->setText("服务器未运行");
        statusBar()->showMessage("服务器已停止");
        
        // 清空客户端列表
        clientListWidget->clear();
        disconnectClientButton->setEnabled(false);
    }
}

void ServerUI::onFrameRateChanged(int fps)
{
    server->setCaptureFrameRate(fps);
}

void ServerUI::onQualityChanged(int quality)
{
    server->setCompressionQuality(quality);
}

void ServerUI::onDiffEncodingToggled(bool enabled)
{
    server->setDiffEncodingEnabled(enabled);
}

void ServerUI::onRemoteControlToggled(bool enabled)
{
    server->setRemoteControlEnabled(enabled);
}

void ServerUI::onPortChanged(int port)
{
    // 仅显示，无需操作，启动时才会应用
    (void)port; // 防止未使用参数警告
}

void ServerUI::onLANDiscoveryToggled(bool enabled)
{
    server->enableLANDiscovery(enabled);
}

void ServerUI::onServerNameChanged()
{
    server->setServerName(serverNameEdit->text());
}

void ServerUI::onClientConnected(const QString &clientId, const QString &clientAddress)
{
    QString displayText = QString("%1 (%2)").arg(clientId).arg(clientAddress);
    QListWidgetItem *item = new QListWidgetItem(displayText, clientListWidget);
    item->setData(Qt::UserRole, clientId);
    
    statusBar()->showMessage(QString("客户端 %1 已连接").arg(clientAddress), 3000);
}

void ServerUI::onClientDisconnected(const QString &clientId)
{
    // 从列表中删除客户端
    for (int i = 0; i < clientListWidget->count(); i++) {
        QListWidgetItem *item = clientListWidget->item(i);
        if (item->data(Qt::UserRole).toString() == clientId) {
            delete clientListWidget->takeItem(i);
            break;
        }
    }
    
    statusBar()->showMessage(QString("客户端 %1 已断开").arg(clientId), 3000);
}

void ServerUI::onDisconnectClientClicked()
{
    QList<QListWidgetItem*> selectedItems = clientListWidget->selectedItems();
    if (selectedItems.isEmpty()) {
        return;
    }
    
    QString clientId = selectedItems.first()->data(Qt::UserRole).toString();
    if (server->disconnectClient(clientId)) {
        statusBar()->showMessage(QString("已断开客户端 %1").arg(clientId), 3000);
    } else {
        statusBar()->showMessage(QString("无法断开客户端 %1").arg(clientId), 3000);
    }
}

void ServerUI::onMouseEventReceived(const QString &clientId, int x, int y, int button, bool pressed)
{
    QString action = pressed ? "按下" : "释放";
    logTextEdit->append(QString("[鼠标] 客户端: %1, 动作: %2, 按钮: %3, 位置: (%4, %5)")
                         .arg(clientId).arg(action).arg(button).arg(x).arg(y));
}

void ServerUI::onKeyboardEventReceived(const QString &clientId, int key, bool pressed)
{
    QString action = pressed ? "按下" : "释放";
    logTextEdit->append(QString("[键盘] 客户端: %1, 动作: %2, 键码: %3")
                         .arg(clientId).arg(action).arg(key));
}

void ServerUI::onErrorOccurred(const QString &errorMsg)
{
    logTextEdit->append(QString("[错误] %1").arg(errorMsg));
    statusBar()->showMessage(QString("错误: %1").arg(errorMsg), 5000);
}

void ServerUI::updateLog()
{
    // 获取最新的日志内容
    QStringList logEntries = Logger::getInstance()->getLatestEntries();
    for (const QString &entry : logEntries) {
        logTextEdit->append(entry);
    }
    
    // 滚动到底部
    QScrollBar *scrollBar = logTextEdit->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
} 